package org.example.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import jakarta.annotation.PostConstruct;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xirtl
 * @date 2025/9/17  10:25
 * @description 阿里巴巴的sentinel限流工具
 */
//配置类步骤：
        //1. 定义限流规则
        //2. 加载限流规则，使用@PostConstruct注解在项目启动时初始化限流的接口。
        // 3.使用FlowRuleManager加载规则。
@Configuration
public class SentinelConfig {
    @Bean
    public SentinelResourceAspect sentineResourceAspect(){
        return new SentinelResourceAspect();
    }
    //初始化sentinel限流规则
    @PostConstruct
    private static void initFlowRules(){
        List<FlowRule> rules=new ArrayList<>();
        //创建订单接口限流规则
        FlowRule orderCreateRule=new FlowRule();
        orderCreateRule.setRefResource("createOrder");
        orderCreateRule.setCount(100);
        orderCreateRule.setGrade(RuleConstant.FLOW_GRADE_QPS); //QPS模式
        orderCreateRule.setLimitApp("default");
        rules.add(orderCreateRule);
        //加载规则
        FlowRuleManager.loadRules(rules);
    }
}
